package com.lzc.email.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Set;

/**
 * Created by lzc
 * 2018/12/13 23:30
 */
@Service
@Slf4j
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender mailSender;// spring 提供的邮件发送类

    @Value("${spring.mail.username}")
    private String from = ""; // 邮件发送人，这里直接从配置文件中获取

    @Override
    public void sendSimpleEmail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();// 创建简单邮件消息
        message.setFrom(from);
        message.setTo(to); //设置收件人
        /* String[] adds = {"xxx@qq.com","yyy@qq.com"}; // 同时发送给多人
        message.setTo(adds);*/
        message.setSubject(subject); // 设置主题
        message.setText(content); // 设置内容
        try {
            mailSender.send(message); // 执行发送邮件
            log.info("简单邮件已经发送。");
        } catch (Exception e) {
            log.error("发送简单邮件时发生异常！", e);
        }
    }

    @Override
    public void sendHtmlEmail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            // true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(message);
            log.info("html邮件发送成功");
        } catch (MessagingException e) {
            log.error("发送html邮件时发生异常！", e);
        }
    }

    @Override
    public void sendAttachmentsEmail(String to, String subject, String content, Set<String> filePaths) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content);
            for (String filePath : filePaths) {
                FileSystemResource file = new FileSystemResource(new File(filePath));
                helper.addAttachment(file.getFilename(), file);
                log.info(file.getFilename());
            }
            mailSender.send(mimeMessage);
            log.info("发送成功");
        } catch (MessagingException e) {
            e.printStackTrace();
            log.info("发送失败" + e);
        }
    }
}
